﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace FrameworkLib.Configuration
{
    public class FLibConfigurationCollection<T> : ConfigurationElementCollection where T : ConfigurationElement, new()
    {
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.AddRemoveClearMap;
            }
        }

        public T this[int index]
        {
            get { return (T)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                    BaseRemoveAt(index);
                BaseAdd(index, value);
            }
        }

        public new T this[string key]
        {
            get { return (T)BaseGet(key); }
        }

        public void Add(T element)
        {
            BaseAdd(element);
        }

        public void Clear()
        {
            BaseClear();
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return (ConfigurationElement)new T();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((T)element).ToString();
        }

        protected override string ElementName
        {
            get
            {
                ConfigurationSectionNameAttribute snAttribute =
                              (ConfigurationSectionNameAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(ConfigurationSectionNameAttribute));

                return snAttribute.SectionName;
            }
        }

        protected override bool IsElementName(string elementName)
        {
            ConfigurationSectionNameAttribute snAttribute =
              (ConfigurationSectionNameAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(ConfigurationSectionNameAttribute));

            return !String.IsNullOrEmpty(elementName) && elementName == snAttribute.SectionName;
        }

        public T GetElement(string key)
        {
            return (T)BaseGet(key);
        }

        public void Remove(T element)
        {
            BaseRemove(element.ToString());
        }

        public void Remove(string name)
        {
            BaseRemove(name);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }
    }
}
